package com.lebang.lechuangsystem.common;

import com.lebang.lechuangsystem.domain.User;
import com.lebang.lechuangsystem.util.RsaUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * session管理
 * @Author: hwq
 * @Date: 2019/8/23 10:22
 * @Version 1.0
 */
public class SessionUtil {
    private static final String USER = "user";
    /**
     * 获取用户session
     * @return
     */
    public static Integer getSessionId() {
        Object id = getHttpSession().getAttribute(USER);
        if(id==null){
            return null;
        }
        String str= null;
        try {
            str = RsaUtil.Decrypt(id.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return Integer.parseInt(str);
    }

    /**
     * 清除session
     */
    public static void removeSession() {
        getHttpSession().removeAttribute(USER);
    }

    /**
     * 保存session
     */
    public static void setSession(User user) {

        try {
            getHttpSession().setAttribute(USER, RsaUtil.Encrypt(user.getId().toString()));
        } catch (Exception e) {

        }
    }

    /**
     * 获取HttpSession对象
     * @return
     */
    private static HttpSession getHttpSession() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        HttpSession session = request.getSession();
        return session;
    }
}
